<template>

  <view class="container">
    <image src="https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/classroom_bg.png" mode="aspectFill"
      class="classroom-img"></image>
    <view class="card">
      <!-- 选项 -->
      <uni-card class="card-q" :title="`单选`" :extra="`第 ${currentIndex + 1} 题 / 共 ${questionList.length} 题`"
        :thumbnail="avatar">
        <!-- 题目 -->
        <view class="question-container">
          <text class="question-text">{{questionList[currentIndex].question}}</text>
        </view>
        <!-- 选项 -->

<!--        <view v-for="(item,index) in questionList[currentIndex].options" :key="item.id" @tap="handleSelectOption(index,item.id)" :class="{'choose': true,
        	'right-active': isRightChoice(index) || index==showRightAnswer, 'wrong-active': isWrongChoice(index)}">
      
          <text class="choose-text">{{item.label}}: {{item.text}}</text>
        </view> -->
        <view v-for="(item,index) in questionList[currentIndex].options" :key="item.id" @tap="handleSelectOption(index,item.id)" :class="{'choose': true,
        	'right-active': item.id==answerId, 'wrong-active': tagChoose&&item.id!=answerId&& chooseId==item.id}">
              
          <text class="choose-text">{{item.label}}: {{item.text}}</text>
        </view>



      </uni-card>

      <!-- 解析 -->
      <!-- <uni-card class="card-a" v-if="isWrongAnswer">
				错误！
				正确答案：{{questionList[currentIndex].answer}}
			</uni-card> -->

      <!-- 确认按钮 -->
      <!-- 			<view class="next-button" v-if="showNextButton" @click="handleNextQuestion">
				<text>下一题</text>
			</view> -->

    </view>

    <!-- 显示成绩的弹窗 -->
    <uni-popup ref="popup" type="center" :mask-click="false">
      <view class="popup-container">


        <image src="https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/header.png" mode="aspectFill"
          class="title"></image>

        <view class="sub-container">
          <view class="text-container">
            <view class="show-info-l"><text class="info-text">正确率：{{submitForm.rightNum/submitForm.total*100}}%</text></view>
            <view class="show-info-r"><text class="info-text">答对数：{{submitForm.rightNum}}</text></view>
          </view>
          <view class="text-container">
            <view class="show-info-l"><text class="info-text">错题数：{{submitForm.total-submitForm.rightNum}}</text></view>
            <view class="show-info-r"><text class="info-text">能量值：+{{submitForm.score}}cc</text>
            </view>
          </view>

        </view>
        <view class="button-container">
          <view @click="clickToClose" class="button-quit">
            <text class="button-text">领取能量</text>

          </view>
          <image src="https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/lion_good.png" mode="aspectFit"
            class="goodpng"></image>
        </view>
      </view>
    </uni-popup>
  </view>

</template>

<script>
  import {
    getQuestion,
    postResult,
    verifyResult,
    submit
  } from "@/api/bag-test.js";
  export default {
    data() {
      return {
        // 字母表
        alph: ['A', 'B', 'C', 'D'],
        // 下标映射
        idMap: {
          A: 0,
          B: 1,
          C: 2,
          D: 3
        },
        // 当前题目的索引
        currentIndex: 0,
        // 存储用户答案
        // selectedAnswers: [],
        // 存储用户当前得分
        // score: 10,
        // 答对一题增加4cc
        // ccPerRight: 4,
        // // 存储回答正确次数
        // rightTime: 0,
        submitForm:{rightNum:"",total:"",score:""},
        // 当前问题是否回答过（实现仅能回答一次）
        tagChoose: false,
        chooseId:0,
        answerId:0,
        // 用户是否回答错误的标志
        // isWrongAnswer: false,
        // 展示下一题按钮tag
        // showNextButton: false,
        // 正确答案显示判断
        // showRightAnswer: -1,
        // 数据
        enterTime:"",
        questionList: [{
            "id": 1,
            "type": "测试134",
            "question": "请问你是？",
            "options": [{
                "id": 1,
                "label": "A",
                "text": "answer A"
              },
              {
                "id": 2,
                "label": "B",
                "text": "answer B"
              },
              {
                "id": 3,
                "label": "C",
                "text": "answer C"
              },
              {
                "id": 4,
                "label": "D",
                "text": "answer D"
              }
            ]
          },
          {
            "id": 3,
            "type": "测试22",
            "question": "ceshi",
            "options": [{
                "id": 9,
                "label": "A",
                "text": "24"
              },
              {
                "id": 10,
                "label": "B",
                "text": "57656"
              },
              {
                "id": 11,
                "label": "C",
                "text": "769"
              },
              {
                "id": 12,
                "label": "D",
                "text": "34535"
              }
            ]
          }
        ],
      };
    },
    onLoad() {
      // this.showPopup();
      this.getQuestionList();
    },
    methods: {
      // 请求题目数据
      getQuestionList() {
        getQuestion().then(res => {
          console.log("请求题目数据");
          console.log("this.questionList", res);
          this.questionList = res.data.data;
          this.enterTime = new Date().format("yyyy-MM-dd");
        })
      },
      // 控制结果弹窗
      showPopup() {
        this.$refs.popup.open();
      },
      postScoreResult() {

        submit()
          .then(response => {
            console.log(response);
            this.submitForm=response.data.data;
            var s1 = new Date().format("yyyy-MM-dd");
         if(s1 != wx.getStorageSync('shenai_last_quiz_date'))
            wx.setStorageSync('shenai_last_quiz_date',s1)
            uni.$emit('needRefresh', true)
            // 处理请求成功的响应数据
          })
          .catch(error => {
            console.error(error);
            // 处理请求失败的错误
          });
      },
      clickToClose() {
      
        uni.navigateBack({
          delta: 1
        });
      },
      // 点击下一题按钮事件
      handleNextQuestion() {
        console.log('点击了下一题');
        // 如果已经是最后一道题目，则弹出提示信息，或者直接调用分数计算
        if (this.currentIndex === this.questionList.length - 1) {
          this.showPopup();
          this.postScoreResult();
          return;
        }
        // 如果不是最后一题，更新本题做完与否的tag，留给下一题用
        if (this.currentIndex !== this.questionList.length - 1) {
          this.tagChoose = false;
        }

        // 下一题
        this.currentIndex++;
      },

      // 选项是否正确
       async ifRight(id) {
        let res= await verifyResult(this.questionList[this.currentIndex].id,id)
          console.log("verifyResult",res)
          this.answerId=res.data.data.answer.id
          if(this.isTomorrow()) {
            uni.showToast({
              title: `今天(`+this.enterTime+`)已经结束了，请重新进入题目~`,
              icon: 'none'
            });
            setTimeout(() => {
              
              // 延时1秒钟后返回
               this.clickToClose();
            }, 1000);
           
          }
          return res.data.data.isRight
           

      },
      // 点击选项事件，传入用户点击的选项序号
      async handleSelectOption(index,id) {
        // 测试
        console.log('点击了', index,id);
        this.chooseId=id
        // 重复检验
        if (!this.tagChoose) {
          // 判断对错
          let isVerify=await this.ifRight(id);
          if (isVerify) {
          
            // 延时后自动进入下一题
            setTimeout(() => {
              // 延时1秒钟后自动进入下一题
              this.handleNextQuestion();
            }, 1000);
          } else {
            // 选择错误
            console.log('错误')


            // // 延时1秒钟后自动进入下一题
            setTimeout(() => {
              this.handleNextQuestion();
            }, 1500);
          }
          // 保存结果（备用）
          // this.saveAnswer(index);
        } else {
          console.log('已经回答过本题');
        }
        // 如果是首次选择本题，tag置为true表示已经选择了本题答案，不允许后面的选择
        this.tagChoose = true;
        // 更新当前选择

      },
      
      //判断是否跨天
      isTomorrow(){
        var s1 = new Date().format("yyyy-MM-dd");
        console.log(s1 == this.enterTime)
        return !(s1 == this.enterTime)
      },
      // 
    
      // 跳转到排行榜页面
      gotoRank() {
        uni.navigateTo({
          url: '/subpkg-bag/bag-rank/bag-rank'
        })
      }

    }

  }
</script>

<style lang="scss">
  .background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: -1;
    /* 将背景图设置为负层级，使其在 view 组件之下 */
  }

  .card {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .card-q {
    margin-top: 90rpx;
    width: 100vw;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .card-a {
    width: 100vw;
  }

  .question-container {
    // margin-top: 10rpx;
    margin-bottom: 20rpx;
  }

  .choose {
    // border: 1rpx solid;
    border-radius: 10rpx;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    box-shadow: 2rpx 2rpx 10rpx #bfbfbf;
    width: 600rpx;
    // width: fit-content;
    // height: 60rpx; // 不设置具体的高度，view组件就会自适应
  }

  .choose-text {
    margin: 15rpx;
  }

  .right-active {
    background-color: #d8dc8f;
    border: 1rpx solid #94ae65;
  }

  .wrong-active {
    background-color: #ff7f6a;
    border: 1rpx solid #f85b48;
  }

  .next-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    // border: 1rpx solid;
    border-radius: 10rpx;
    margin-top: 30rpx;
    width: 90vw;
    height: 70rpx;
    color: white;
    box-shadow: 2rpx 2rpx 10rpx #bfbfbf;
    background-color: #fefbe7;
  }

  .popup-container {
    display: flex;
    flex-direction: column;
    background-color: rgba(255, 255, 255, 1);
    border-radius: 20rpx;
    // width: 550rpx;
    width: 80vw;
    height: 60vh;
    align-items: center;
  }

  .title {
    width: 80vw;
    height: 20vh;
    border-radius: 20rpx 20rpx 0 0;
  }

  .show-info-l {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-left: 3vw;
    height: 5vh;
    width: 30vw;
  }

  .show-info-r {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-left: 5vw;
    height: 5vh;
    width: 30vw;
  }

  .sub-container {
    display: flex;
    flex-direction: column;
    width: 80vw;
    margin-top: 22rpx;

  }

  .text-container {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: relative;
    top: 3vh;
    // margin-bottom: 2vh;
  }

  .info-text {
    font-size: 25rpx;
    color: gray;

  }

  .button-quit {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 20rpx;
    // border: 1rpx solid;
    height: 90rpx;
    width: 500rpx;
    margin: 20rpx;
    background-color: #ef8671;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    position: relative;
    top: 17vh;
    // left: 132rpx;
    z-index: 1
  }

  .button-text {
    color: white;
  }

  .classroom-img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: -1;
  }

  .goodpng {
    position: absolute;
    height: 218rpx;
    width: 320rpx;
    position: relative;
    left: -47rpx;
    opacity: 0.5;
    top: -80rpx;
  }
</style>